package com.gsww.vue.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class BasicService{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	/**
	 * 
	 * @Title: page  
	 * @Description:  (不传参的分页) 
	 * @author hanjp   
	 * @param @param sql		sql语句
	 * @param @param pageNo		页码
	 * @param @param pageSize	页大小
	 * @param @return    参数  
	 * @return Map<String,Object>    返回类型
	 * @date 2018年7月12日 上午11:26:08  
	 * @throws
	 */
	public Map<String, Object> page(String sql,List<Object> params,String page_no,String page_size) throws Exception{
		int pageNo = Integer.parseInt(page_no);
		int pageSize = Integer.parseInt(page_size);
		Map<String,Object> pagemap = new HashMap<>(50);
		String pageSql = "";
		try {
			int allmap = jdbcTemplate.queryForObject("select count(1) from (" + sql + ")  t",Integer.class,params.toArray());
			//mysql
			sql+=" LIMIT "+(pageNo-1)*pageSize+","+pageSize; 
//			pageSql = "select * from ("+  
//						"SELECT A.*, ROWNUM RN "+  
//						" FROM ("+sql+") A"+  
//						")  WHERE RN BETWEEN ? AND ?  ";	
			//System.out.println(pageSql);
//			params.add((pageNo-1)*pageSize+1);
//			params.add(pageNo*pageSize);
			List<Map<String, Object>> map = jdbcTemplate.queryForList(sql,params.toArray());
			pagemap.put("result", map);
			pagemap.put("sql", sql);
			pagemap.put("totalPage",  allmap % pageSize==0 ? allmap / pageSize : allmap / pageSize + 1);
			pagemap.put("totalRow", allmap);
		} catch (Exception e) {
			e.printStackTrace();
			pagemap.put("result", null);
			pagemap.put("sql", pageSql);
			pagemap.put("totalPage",  0);
			pagemap.put("totalRow", 0);
		}
		
		return pagemap;
	}
}